package pl.olap.gui;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;

import pl.olap.dao.Movie;
import pl.olap.persistence.SearchUtil;

public class LeftPanel extends JPanel {

	/** serialization uid */
	private static final long serialVersionUID = -2596853981965669104L;

	private RightPanel rightPanel = null;

	private JTable table = null;
	private JScrollPane pane = null;

	private String[] columnNames = { "Id.", "Tytuł", "Opis", "Ocena" };

	private Map<String, Movie> movieMap = null;

	public LeftPanel(RightPanel r) {
		// ustawiam border
		Border b = BorderFactory.createLoweredBevelBorder();
		setBorder(b);
		this.rightPanel = r;

		// dodajemy tabele z wynikami wyszukiwania
		Object[][] data = new Object[1][4];
		this.table = new JTable(data, columnNames);
		pane = new JScrollPane(table);
		table.setFillsViewportHeight(true);
		add(pane, BorderLayout.CENTER);
	}

	/**
	 * @return the rightPanel
	 */
	public RightPanel getRightPanel() {
		return rightPanel;
	}

	/**
	 * @param rightPanel
	 *            the rightPanel to set
	 */
	public void setRightPanel(RightPanel rightPanel) {
		this.rightPanel = rightPanel;
	}

	public void setMovies(List<Movie> movies) {
		pane.remove(table);
		this.remove(pane);

		Object[][] data = new Object[movies.size()][4];
		movieMap = new HashMap<String, Movie>();
		int i = 0;
		for (Movie m : movies) {
			data[i][0] = m.getIdMovie().toString();
			data[i][1] = m.getTitle();
			data[i][2] = m.getDescription();
			data[i][3] = m.getRating();
			movieMap.put(m.getIdMovie().toString(), m);
			i++;
		}
		this.table = new JTable();
		DefaultTableModel tableModel = new DefaultTableModel(data, columnNames) {

			@Override
			public boolean isCellEditable(int row, int column) {
				// all cells false
				return false;
			}
		};
		table.setModel(tableModel);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					JTable target = (JTable) e.getSource();
					int row = target.getSelectedRow();
					int column = target.getSelectedColumn();
					// do some action
					String id = target.getModel().getValueAt(row, 0).toString();
					Movie m = movieMap.get(id);
					rightPanel.setMovie(m);
				}
			}
		});
		// table.setEnabled(false);

		pane = new JScrollPane(table);
		this.add(pane, BorderLayout.CENTER);

		this.updateUI();
		this.repaint();

	}
}
